<template>
  <view class="cu-filter-dict-label-container">
    <view class="title">{{ title }}</view>
    <view class="filter-dict-label">
      <view
        :class="{ active: active == item.dictValue }"
        v-for="item in listData"
        :key="item.dictValue"
        @click="clickHandler(item)"
        >{{ item.dictLabel }}</view
      >
    </view>
  </view>
</template>

<script>
import { getDicts } from '@/api/system/dict.js'
export default {
  name: 'CuFilterDictLabel',
  model: {
    prop: 'value',
    event: 'update:value'
  },
  data() {
    return {
      listData: [],
      // 选中的元素
      active: undefined
    }
  },
  props: {
    value: {
      type: [Number, Array, String, Boolean]
    },
    title: {
      type: String
    },
    dictType: {
      type: String
    },
    dictList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    dictType: {
      async handler(newVal, oldVal) {
        if (newVal != oldVal) {
          this.getDicts(newVal)
        }
      },
      deep: true,
      immediate: true
    },
    dictList: {
      async handler(newVal, oldVal) {
        if (newVal != oldVal) {
          this.listData = newVal
        }
      },
      deep: true,
      immediate: true
    },
    value: {
      async handler(val) {
        if (val == this.active) return
        this.active = val
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 获取字典数据
    getDicts(val) {
      getDicts(val).then((res) => {
        this.listData = res.data
      })
    },
    // 点击选中，再次点击取消选中
    clickHandler(item) {
      this.active = this.active == item.dictValue ? undefined : item.dictValue
      this.$emit('update:value', this.active)
    }
  }
}
</script>

<style lang="scss" scoped>
.cu-filter-dict-label-container {
  padding-bottom: 40rpx;

  .title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333333;
    padding: 0 0 20rpx 30rpx;
  }

  .filter-dict-label {
    display: grid;
    grid-template-columns: 92px 92px 92px;
    grid-row-gap: 15px;
    grid-column-gap: 15px;
    justify-content: center;
    padding: 0 30rpx;
    > view {
      width: 184rpx;
      text-align: center;
      line-height: 56rpx;
      background: #f8f8f8;
      border-radius: 28rpx;
      font-size: 26rpx;
      color: #333333;
      border: 2rpx solid #f8f8f8;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      padding: 0 20rpx;

      &.active {
        font-weight: bold;
        color: #88b4c4;
        background: #e3eff3;
        border: 2rpx solid #88b4c4;
      }
    }
  }
}
</style>
